﻿using System.Globalization;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.ProcessConfiguration.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Schema;

namespace SetupTfsDemo
{
    class Program
    {
        private static TfsTeamProjectCollection _tfs;
        private static ProjectInfo _selectedTeamProject;
        private static WorkItemStore _wis;
        private static TfsTeamService _tts;
        private static TeamSettingsConfigurationService _teamConfig;
        private static IIdentityManagementService2 _ids;
        private static ICommonStructureService4 _css;

        private static readonly DemoDictionary DemoDictionary = new DemoDictionary();
        static readonly Dictionary<string, string> QueryAndGuid = new Dictionary<string, string>();
        private static TeamFoundationTeam _team;
        private static TeamConfiguration _teamSettings;

        public static bool ConnectToTfs()
        {
            var isSelected = false;
            var tfsPp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            tfsPp.ShowDialog();
            _tfs = tfsPp.SelectedTeamProjectCollection;

            if (tfsPp.SelectedProjects.Any())
            {
                _selectedTeamProject = tfsPp.SelectedProjects[0];
                isSelected = true;
            }

            return isSelected;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("> Continue setting up TFS Demo setup?{0}Yes [Y] No [N]{0}>", Environment.NewLine);

            if (Console.ReadKey().Key.ToString().ToUpper() == "Y")
            {
                ValidateConfig();

                Console.WriteLine("{0}{0}> Please select the team project you would like to set up for Demo {0}",
                                  Environment.NewLine);

                if (ConnectToTfs() && _selectedTeamProject != null)
                {
                    _wis = _tfs.GetService<WorkItemStore>();
                    _teamConfig = _tfs.GetService<TeamSettingsConfigurationService>();
                    _css = _tfs.GetService<ICommonStructureService4>();
                    _tts = _tfs.GetService<TfsTeamService>();

                    Console.WriteLine("{0}> Reading DemoDictionary xml file for setup instructions", Environment.NewLine);

                    ParseConfig();

                    Console.WriteLine("> Configure: TeamSettings - '{0}'", DemoDictionary.TeamSetting.Run);

                    if (Convert.ToBoolean(DemoDictionary.TeamSetting.Run))
                    {
                        Console.WriteLine("{0}>> Creating a new Team", Environment.NewLine);

                        if (_tts.QueryTeams(_selectedTeamProject.Uri).Any(t => t.Name == DemoDictionary.TeamSetting.Name))
                        {
                            Console.WriteLine(
                                "{0}>> The team '{1}' already exists in '{2}'.{0}>> Please rename the team or set the run flag to false for team creation in the DemoDictionary.xml.{0}",
                                Environment.NewLine, DemoDictionary.TeamSetting.Name, _selectedTeamProject.Name);
                            Console.ReadKey();
                            return;
                        }

                        // Create a new team
                        CommunityTfsTeamTools.TfsTeams.TfsTeams.Program.Main(new[]
                                                                                 {
                                                                                     "CreateTeam",
                                                                                     string.Format("/Team:{0}",
                                                                                                   DemoDictionary.
                                                                                                       TeamSetting.Name)
                                                                                     ,
                                                                                     string.Format("/Description:{0}",
                                                                                                   DemoDictionary.
                                                                                                       TeamSetting.
                                                                                                       Description),
                                                                                     string.Format(@"/Collection:{0}",
                                                                                                   _tfs.Uri),
                                                                                     string.Format(@"/teamproject:{0}",
                                                                                                   _selectedTeamProject.
                                                                                                       Name)
                                                                                 });



                        Console.WriteLine("{0}>> Set {1} as default team - {2}", Environment.NewLine,
                                          DemoDictionary.TeamSetting.Name, DemoDictionary.TeamSetting.SetAsDefaultTeam);

                        // Set this as the default team
                        if (Convert.ToBoolean(DemoDictionary.TeamSetting.SetAsDefaultTeam))
                        {
                            CommunityTfsTeamTools.TfsTeams.TfsTeams.Program.Main(new[]
                                                                                     {
                                                                                         "SetDefaultTeam",
                                                                                         string.Format("/Team:{0}",
                                                                                                       DemoDictionary.
                                                                                                           TeamSetting.
                                                                                                           Name),
                                                                                         string.Format(
                                                                                             @"/Collection:{0}",
                                                                                             _tfs.Uri),
                                                                                         string.Format(
                                                                                             @"/teamproject:{0}",
                                                                                             _selectedTeamProject.Name)
                                                                                     });
                        }

                        Console.WriteLine("{0}>> Evaluating Team Settings", Environment.NewLine);

                        // Configure Team Settings
                        _team =
                            _tts.QueryTeams(_selectedTeamProject.Uri).FirstOrDefault(
                                t => t.Name == DemoDictionary.TeamSetting.Name);

                        if (_team != null)
                        {
                            var team =
                                _teamConfig.GetTeamConfigurations(new[] { _team.Identity.TeamFoundationId }).
                                    FirstOrDefault();

                            Console.WriteLine("{0}>> Evaluating Team Backlog Iteration Path", Environment.NewLine);
                            if (team != null)
                            {
                                var ts = team.TeamSettings;
                                ts.BacklogIterationPath = string.Format(@"{0}\{1}", _selectedTeamProject.Name,
                                                                        DemoDictionary.TeamSetting.BacklogIterationPath);

                                Console.WriteLine("{0}>> Evaluating Iteration Path & Dates", Environment.NewLine);

                                var its = new List<string>();
                                foreach (var iteration in DemoDictionary.TeamSetting.Iterations)
                                {
                                    var it = string.Format(@"{0}\{1}", _selectedTeamProject.Name, iteration.Path);
                                    its.Add(it);

                                    var projectNameIndex = it.IndexOf("\\", 2, StringComparison.Ordinal);
                                    var fullPath = it.Insert(projectNameIndex, "\\Iteration");
                                    var nodeInfo = _css.GetNodeFromPath(fullPath);

                                    _css.SetIterationDates(nodeInfo.Uri, iteration.StartDate, iteration.FinishDate);
                                }

                                ts.IterationPaths = its.ToArray();
                                // DemoDictionary.TeamSetting.Iterations.Select(i => i.Path).ToArray();

                                Console.WriteLine("{0}>> Evaluating Team Area Path", Environment.NewLine);

                                var tfv = new TeamFieldValue { IncludeChildren = true, Value = _selectedTeamProject.Name };
                                ts.TeamFieldValues = new[] { tfv };

                                Console.WriteLine("{0}>> Committing Team Settings", Environment.NewLine);
                                _teamConfig.SetTeamSettings(team.TeamId, ts);
                            }
                        }
                    }

                    _team =
                        _tts.QueryTeams(_selectedTeamProject.Uri).FirstOrDefault(
                            t => t.Name == DemoDictionary.TeamSetting.Name);
                    _teamSettings =
                        _teamConfig.GetTeamConfigurations(new[] { _team.Identity.TeamFoundationId }).FirstOrDefault();

                    Console.WriteLine("> Configure: Team Members - '{0}' ", DemoDictionary.TeamMembers.Run);

                    if (DemoDictionary.TeamMembers.Run)
                    {
                        Console.WriteLine("{0}>> Adding Team Members", Environment.NewLine);

                        // Add members to the team
                        foreach (var tm in DemoDictionary.TeamMembers.TeamMember)
                        {
                            CommunityTfsTeamTools.TfsTeams.TfsTeams.Program.Main(new[]
                                                                                     {
                                                                                         "AddUser",
                                                                                         string.Format("/User:{0}",
                                                                                                       tm.User),
                                                                                         string.Format("/Team:{0}",
                                                                                                       DemoDictionary.
                                                                                                           TeamSetting.
                                                                                                           Name),
                                                                                         string.Format(
                                                                                             @"/Collection:{0}",
                                                                                             _tfs.Uri),
                                                                                         string.Format(
                                                                                             @"/teamproject:{0}",
                                                                                             _selectedTeamProject.Name)
                                                                                     });
                        }
                    }

                    // Adding Favorites to the taskboard
                    Console.WriteLine("> Configure: Team Favorites - '{0}' ", DemoDictionary.TeamFavorites.Run);
                    GetQueryGuidList(_wis.Projects[_selectedTeamProject.Name].QueryHierarchy);

                    if (Convert.ToBoolean(DemoDictionary.TeamFavorites.Run))
                    {
                        foreach (var teamFavorite in DemoDictionary.TeamFavorites.TeamFavorite)
                        {
                            switch (teamFavorite.Type.ToLower())
                            {
                                case "query":

                                    Console.WriteLine("{0}>> Evaluating '{1}' - '{2}' as a favorite",
                                                      Environment.NewLine,
                                                      teamFavorite.Type, teamFavorite.Name);

                                    ConfigureTeamFavorites(DemoDictionary.TeamSetting.Name, teamFavorite.Name);

                                    break;
                                case "buildDefinition":

                                    Console.WriteLine("{0}>> Evaluating '{1}' - '{2}' as a favorite",
                                                      Environment.NewLine,
                                                      teamFavorite.Type, teamFavorite.Name);

                                    break;
                                default:
                                    Console.WriteLine("{0}>> Favorite Type '{1}' Not found", Environment.NewLine,
                                                      teamFavorite.Type);
                                    break;
                            }
                        }
                    }

                    Console.WriteLine("> Configure Work Items - '{0}' ", DemoDictionary.WorkItems.Run);

                    if (DemoDictionary.WorkItems.Run)
                    {
                        Console.WriteLine("{0}>> Adding WorkItems", Environment.NewLine);

                        // Add work Items to sprint
                        foreach (var workItem in DemoDictionary.WorkItems.WorkItem)
                        {
                            var p =
                                new WorkItem(
                                    _wis.Projects[_selectedTeamProject.Name].WorkItemTypes["Product Backlog Item"]);
                            p.Title = workItem.ProductBacklogItem.Title;
                            p.Description = workItem.ProductBacklogItem.Description;
                            p.IterationPath = _teamSettings.TeamSettings.CurrentIterationPath;
                            // string.Format("{0}\\Release 1\\Sprint 1", _selectedTeamProject.Name);
                            p.AreaPath = _selectedTeamProject.Name;
                            p["Assigned To"] = UserName(DemoDictionary.TeamSetting.Name,
                                                        workItem.ProductBacklogItem.AssignedTo);
                            p["Effort"] = workItem.ProductBacklogItem.Effort;

                            if (p.Validate().Count == 0)
                            {
                                p.Save();

                                if ((string)p["Assigned To"] == string.Empty)
                                    Console.WriteLine(
                                        ">> Work Item '{0}' created but not assigned to '{1}' since user isn't a valid user in TPC '{2}' ",
                                        p.Id, workItem.ProductBacklogItem.AssignedTo, _tfs.Name);
                            }
                            else
                            {
                                Console.WriteLine(">> Following exception(s) encountered during work item save: ");
                                foreach (var e in p.Validate())
                                {
                                    Console.WriteLine(" - '{0}' ", e);
                                }
                            }

                            foreach (var task in workItem.Task)
                            {
                                var t = new WorkItem(_wis.Projects[_selectedTeamProject.Name].WorkItemTypes["Task"]);
                                t.Title = task.Title;
                                t.Description = task.Description;
                                t.IterationPath = _teamSettings.TeamSettings.CurrentIterationPath;
                                // string.Format("{0}\\Release 1\\Sprint 1", _selectedTeamProject.Name);
                                t.AreaPath = _selectedTeamProject.Name;
                                t["Assigned To"] = UserName(DemoDictionary.TeamSetting.Name, task.AssignedTo);
                                t["Remaining Work"] = task.RemainingWork;

                                if (t.Validate().Count == 0)
                                {
                                    t.Save();

                                    if ((string)t["Assigned To"] == string.Empty)
                                        Console.WriteLine(
                                            ">> Work Item '{0}' created but not assigned to '{1}' since user isn't a valid user in TPC '{2}' ",
                                            t.Id, task.AssignedTo, _tfs.Name);
                                }
                                else
                                {
                                    Console.WriteLine(">> Following exception(s) encountered during work item save: ");
                                    foreach (var e in t.Validate())
                                    {
                                        Console.WriteLine(" - '{0}' ", e);
                                    }
                                }

                                var linkTypEnd = _wis.WorkItemLinkTypes.LinkTypeEnds["Child"];
                                p.Links.Add(new WorkItemLink(linkTypEnd, t.Id));

                                if (p.Validate().Count == 0)
                                {
                                    p.Save();
                                }
                                else
                                {
                                    Console.WriteLine(">> Following exception(s) encountered during work item save: ");
                                    foreach (var e in p.Validate())
                                    {
                                        Console.WriteLine(" - '{0}' ", e);
                                    }
                                }
                            }
                        }
                    }
                    Console.WriteLine("{0}Press any key to Exit!", Environment.NewLine);
                    Console.ReadKey();
                }
                else
                {
                    Console.WriteLine("{0}Press any key to Exit!", Environment.NewLine);
                    Console.ReadKey();
                }
            }
        }

        // Get the Total effort remaining in the current sprint
        private static decimal QueryTaskTotalEfforRemaining()
        {
            var unfinishedWorkInCurrentSprint =
                            _wis.GetQueryDefinition(
                                new Guid(QueryAndGuid.FirstOrDefault(c => c.Key == "Unfinished Work").Value));

            var parameters = new Dictionary<string, object> { { "project", _selectedTeamProject.Name } };
            var q = new Query(_wis, unfinishedWorkInCurrentSprint.QueryText, parameters);
            var results = q.RunLinkQuery();

            var wis = new List<WorkItem>();

            foreach (var result in results)
            {
                var _wi = _wis.GetWorkItem(result.TargetId);
                if (_wi.Type.Name == "Task")
                    wis.Add(_wi);
            }
            return wis.Sum(r => Convert.ToDecimal(r["Remaining Work"]));
        }

        private static List<WorkItem> GetAllTaskTypeUnfinsihedWorkItems()
        {
            var unfinishedWorkInCurrentSprint =
                            _wis.GetQueryDefinition(
                                new Guid(QueryAndGuid.FirstOrDefault(c => c.Key == "Unfinished Work").Value));

            var parameters = new Dictionary<string, object> { { "project", _selectedTeamProject.Name } };
            var q = new Query(_wis, unfinishedWorkInCurrentSprint.QueryText, parameters);
            var results = q.RunLinkQuery();

            var wis = new List<WorkItem>();

            foreach (var result in results)
            {
                var _wi = _wis.GetWorkItem(result.TargetId);
                if (_wi.Type.Name == "Task")
                    wis.Add(_wi);
            }
            return wis;
        }

        private static void ParseConfig()
        {
            var doc = XDocument.Load(Constants.Uri);
            if (doc.Root == null) return;
            var ns = doc.Root.Name.Namespace;

            // Team Setting
            var ts = new DemoDictionaryTeamSetting();
            GetTeamSettings(ns, doc, ts);

            // Team Favorites
            var tfs = new DemoDictionaryTeamFavorites();
            GetTeamFavorites(doc, ns, tfs);

            // Team Members
            var tms = new DemoDictionaryTeamMembers();
            GetTeamMembers(doc, ns, tms);

            // Work Items
            var wis = new DemoDictionaryWorkItems();
            GetWorkItems(doc, ns, wis);

            // Assign
            DemoDictionary.TeamSetting = ts;
            DemoDictionary.TeamFavorites = tfs;
            DemoDictionary.TeamMembers = tms;
            DemoDictionary.WorkItems = wis;
        }

        private static void GetWorkItems(XContainer doc, XNamespace ns, DemoDictionaryWorkItems wis)
        {
            if (doc == null) throw new ArgumentNullException("doc");
            var workItems = doc.Descendants(ns + "WorkItems").FirstOrDefault();
            if (workItems != null)
            {
                var run = workItems.Attribute("Run");
                if (run != null)
                    wis.Run = Convert.ToBoolean(run.Value);
            }

            var wi = new List<DemoDictionaryWorkItemsWorkItem>();
            var items = doc.Descendants(ns + "WorkItem");

            foreach (var item in items)
            {
                var w = new DemoDictionaryWorkItemsWorkItem();
                var pbi = new DemoDictionaryWorkItemsWorkItemProductBacklogItem();

                var productBacklogItem = item.Descendants(ns + "ProductBacklogItem").FirstOrDefault();

                if (productBacklogItem != null)
                {
                    var pTitle = productBacklogItem.Element(ns + "Title");
                    if (pTitle != null)
                        pbi.Title = pTitle.Value;
                    var pDescription = productBacklogItem.Element(ns + "Description");
                    if (pDescription != null)
                        pbi.Description = pDescription.Value;
                    var pAssignedTo = productBacklogItem.Element(ns + "AssignedTo");
                    if (pAssignedTo != null)
                        pbi.AssignedTo = pAssignedTo.Value;
                    var pEffort = productBacklogItem.Element(ns + "Effort");
                    if (pEffort != null)
                        pbi.Effort = Convert.ToDecimal(pEffort.Value);
                }

                w.ProductBacklogItem = pbi;

                var tasks = item.Descendants(ns + "Task");
                var tks = new List<DemoDictionaryWorkItemsWorkItemTask>();

                foreach (var task in tasks)
                {
                    var t = new DemoDictionaryWorkItemsWorkItemTask();
                    var tTitle = task.Element(ns + "Title");
                    if (tTitle != null)
                        t.Title = tTitle.Value;
                    var tDescription = task.Element(ns + "Description");
                    if (tDescription != null)
                        t.Description = tDescription.Value;
                    var tAssignedTo = task.Element(ns + "AssignedTo");
                    if (tAssignedTo != null)
                        t.AssignedTo = tAssignedTo.Value;
                    var tRemainingWork = task.Element(ns + "RemainingWork");
                    if (tRemainingWork != null)
                        t.RemainingWork = Convert.ToDecimal(tRemainingWork.Value);
                    tks.Add(t);
                }
                w.Task = tks.ToArray();

                wi.Add(w);
            }
            wis.WorkItem = wi.ToArray();
        }

        private static void GetTeamMembers(XDocument doc, XNamespace ns, DemoDictionaryTeamMembers tms)
        {
            var teamMembers = doc.Descendants(ns + "TeamMembers").FirstOrDefault();
            if (teamMembers == null) return;

            var run = teamMembers.Attribute("Run");
            if (run != null)
                tms.Run = Convert.ToBoolean(run.Value);

            var tm = new List<DemoDictionaryTeamMembersTeamMember>();
            var members = doc.Descendants(ns + "TeamMember");

            foreach (var member in members)
            {
                var m = new DemoDictionaryTeamMembersTeamMember();

                var user = member.Element(ns + "User");
                if (user != null)
                    m.User = user.Value;

                tm.Add(m);
            }
            tms.TeamMember = tm.ToArray();
        }

        private static void GetTeamFavorites(XDocument doc, XNamespace ns, DemoDictionaryTeamFavorites tfs)
        {
            var teamFavorites = doc.Descendants(ns + "TeamFavorites").FirstOrDefault();
            if (teamFavorites != null)
            {
                var run = teamFavorites.Attribute("Run");
                if (run != null)
                    tfs.Run = Convert.ToBoolean(run.Value);
            }

            var tf = new List<DemoDictionaryTeamFavoritesTeamFavorite>();
            var favorites = doc.Descendants(ns + "TeamFavorite");

            foreach (var favorite in favorites)
            {
                var f = new DemoDictionaryTeamFavoritesTeamFavorite();

                var name = favorite.Element(ns + "Name");
                if (name != null)
                    f.Name = name.Value;

                var type = favorite.Element(ns + "Type");
                if (type != null)
                    f.Type = type.Value;

                tf.Add(f);
            }
            tfs.TeamFavorite = tf.ToArray();
        }

        private static void GetIterations(XContainer doc, XNamespace ns, ICollection<DemoDictionaryTeamSettingIteration> its)
        {
            var iterations = doc.Descendants(ns + "Iteration");

            foreach (var iteration in iterations)
            {
                var it = new DemoDictionaryTeamSettingIteration();

                var path = iteration.Element(ns + "Path");
                if (path != null)
                    it.Path = path.Value;

                var startDate = iteration.Element(ns + "StartDate");
                if (startDate != null)
                    it.StartDate = Convert.ToDateTime(startDate.Value);

                var finishDate = iteration.Element(ns + "FinishDate");
                if (finishDate != null)
                    it.FinishDate = Convert.ToDateTime(finishDate.Value);

                its.Add(it);
            }
        }

        private static void GetTeamSettings(XNamespace ns, XContainer doc, DemoDictionaryTeamSetting ts)
        {
            var its = new List<DemoDictionaryTeamSettingIteration>();

            // Team Setting
            GetTeamSetting(doc, ns, ts);

            // Iterations
            GetIterations(doc, ns, its);

            ts.Iterations = its.ToArray();
        }

        private static void GetTeamSetting(XContainer doc, XNamespace ns, DemoDictionaryTeamSetting ts)
        {
            var teamSetting = doc.Descendants(ns + Constants.TeamSetting).FirstOrDefault();
            if (teamSetting == null) return;

            var run = teamSetting.Attribute(Constants.Run);
            if (run != null)
                ts.Run = Convert.ToBoolean(run.Value);

            var name = teamSetting.Element(ns + Constants.Name);
            if (name != null)
                ts.Name = name.Value;

            var description = teamSetting.Element(ns + Constants.Description);
            if (description != null)
                ts.Description = description.Value;

            var setAsDefaultTeam = teamSetting.Element(ns + Constants.SetAsDefaultTeam);
            if (setAsDefaultTeam != null)
                ts.SetAsDefaultTeam = Convert.ToBoolean(setAsDefaultTeam.Value);

            var backlogIterationPath = teamSetting.Element(ns + Constants.BacklogIterationPath);
            if (backlogIterationPath != null)
                ts.BacklogIterationPath = backlogIterationPath.Value;
        }

        private static void ValidateConfig()
        {
            var schema = new XmlSchemaSet();
            schema.Add(Constants.Namespace, Constants.SchemaUri);

            var doc = XDocument.Load(Constants.Uri);
            var errors = false;
            doc.Validate(schema, (o, e) =>
            {
                Console.WriteLine("{0}{1}", Environment.NewLine, e.Message);
                errors = true;
            });

            Console.WriteLine("{0}{0}{1} {2}{0}", Environment.NewLine, Constants.Uri, errors ? "did not validate" : "validated");

            if (errors)
            {
                Console.WriteLine("Fix DemoDictionary.xml and retry...");
                Console.WriteLine("{0}{0}Press any key to Exit!{0}", Environment.NewLine);
                Console.ReadKey();
            }

        }

        private static void GetQueryGuidList(IEnumerable<QueryItem> query)
        {
            foreach (var subQuery in query)
            {
                if (subQuery.GetType() == typeof(QueryFolder))
                    GetQueryGuidList((QueryFolder)subQuery);
                else
                {
                    if (!QueryAndGuid.ContainsKey(subQuery.Name))
                        QueryAndGuid.Add(subQuery.Name, subQuery.Id.ToString());
                }
            }
        }

        private static void ConfigureTeamFavorites(string teamName, string queryName)
        {
            _ids = _tfs.GetService<IIdentityManagementService2>();
            var g = Guid.NewGuid();
            var guid = string.Empty;

            var teamDetail = _tts.QueryTeams(_selectedTeamProject.Uri).FirstOrDefault(t => t.Name == teamName);

            foreach (var q in QueryAndGuid.Where(q => q.Key == queryName))
            {
                guid = q.Value;
            }

            if (guid == string.Empty)
            {
                Console.WriteLine("Query '{0}' - Not found!", queryName);
                return;
            }

            if (teamDetail != null)
            {
                var key =
                    string.Format(
                        "Microsoft.TeamFoundation.Framework.Server.IdentityFavorites..{0}.{1}.WorkItemTracking.Queries{2}",
                        new Uri(_selectedTeamProject.Uri).Segments.LastOrDefault(), teamDetail.Identity.TeamFoundationId,
                        g);

                var value =
                    string.Format(
                        @"{0}""data"":""{1}"",""id"":""{2}"",""name"":""{3}"",""type"":""Microsoft.TeamFoundation.WorkItemTracking.QueryItem""{4}",
                        "{", guid, g, QueryAndGuid.FirstOrDefault(q => q.Value == guid).Key, "}");

                teamDetail.Identity.SetProperty(IdentityPropertyScope.Local, key, value);
            }
            if (teamDetail != null) _ids.UpdateExtendedProperties(teamDetail.Identity);

            Console.WriteLine("{0}Added Query '{1}' as Favorite", Environment.NewLine, queryName);
        }

        private static string UserName(string teamName, string assignedTo)
        {
            // Validate if the user in the config is actually part of the team
            // var teamDetail =
            //              _tts.QueryTeams(_selectedTeamProject.Uri).FirstOrDefault(t => t.Name == teamName);

            if (_team != null)
                foreach (var tm in _team.GetMembers(_tfs, MembershipQuery.Expanded))
                {
                    if (tm.DisplayName == assignedTo)
                    {
                        return tm.DisplayName;
                    }
                }
            Console.WriteLine(">> The user '{0}' is not a valid user in the TPC", assignedTo);
            return string.Empty;
        }
    }
}
